package com.hyfrogx.common.qcloud;

import cn.hutool.core.codec.Base64;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * TODO 文件上传签名
 *
 * @项目 hyplatform
 *
 * @日期: 2017年6月13日
 *
 * @负责人: Orchid
 */
@Configuration
@ConfigurationProperties(prefix = "qcloud")
//@Component
public class GameUtils {

	// 正式服务器的腾讯云控制台配置
	// 云API密钥SecretId
	public static String SecretId;

	// 云API密钥StrSecKey
	public static String StrSecKey;

	// bucket名称
	public static String bucket;

	// 直播点播appId
	public static String appId;

	// 地域信息
	public static String region;

	//@Value("${qcloud.SecretId}")
	public void setSecretId(String SecretId) {
		GameUtils.SecretId = SecretId;
	}

	//@Value("${qcloud.StrSecKey}")
	public void setStrSecKey(String StrSecKey){
		GameUtils.StrSecKey = StrSecKey;
	}

	//@Value("${qcloud.bucket}")
	public void setBucket(String bucket){
		GameUtils.bucket = bucket;
	}

	//@Value("${qcloud.appId}")
	public void setAppId(String appId){
		GameUtils.appId = appId;
	}

	//@Value("${qcloud.region}")
	public void setRegion(String region){
		GameUtils.region = region;
	}


	// 公共签名方法参数，发布时不用注释
	// public int m_iSignValidDuration = 3600 * 24 * 60;
	private static final String CONTENT_CHARSET = "UTF-8";
	public static final String HmacSHA1 = "HmacSHA1";
	public static final String HmacSHA256 = "HmacSHA256";

	private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
			'e', 'f' };

	/**
	 * 签名目前有问题,暂时丢弃
	 *
	 * @brief 签名
	 * @param signStr
	 *            被加密串
	 * @param secret
	 *            加密密钥
	 * @param signatureMethod
	 *            签名算法
	 *
	 * @return
	 */
	@Deprecated
	public static String sign(String signStr, String secret, String signatureMethod)
			throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
		String sig = null;
		Mac mac1 = Mac.getInstance("HmacSHA1");
		Mac mac2 = Mac.getInstance("HmacSHA256");
		byte[] hash;
		if (signatureMethod == "HmacSHA256") {
			SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(CONTENT_CHARSET), mac2.getAlgorithm());
			mac2.init(secretKey);
			hash = mac2.doFinal(signStr.getBytes(CONTENT_CHARSET));
		} else {
			SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(CONTENT_CHARSET), mac1.getAlgorithm());
			mac1.init(secretKey);
			hash = mac1.doFinal(signStr.getBytes(CONTENT_CHARSET));
		}
		sig = new String(Base64.encode(hash));
		return sig;
	}

	/**
	 * 当前UNIX时间戳，可记录发起API请求的时间。
	 *
	 * @return
	 */
	public static long getTimestamp() {
		long time = System.currentTimeMillis() / 1000;
		return time;
	}

	/**
	 * 随机正整数，与 Timestamp 联合起来, 用于防止重放攻击。
	 *
	 * @return
	 */
	public static int getNonce() {
		int random = new Random().nextInt(Integer.MAX_VALUE);
		return random;
	}

	public static byte[] byteMerger(byte[] byte_1, byte[] byte_2) {
		byte[] byte_3 = new byte[byte_1.length + byte_2.length];
		System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
		System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
		return byte_3;
	}

	/**
	 * 加载系统配置文件
	 */
//	public static void loadQCloudPropertys() {
//		Properties properties;
//		properties = loadProperties("Tencent.properties");
//		// 如果配置保留的是正式服务器配置
//		if (null != properties) {
//			Iterator<String> it = properties.stringPropertyNames().iterator();
//			while (it.hasNext()) {
//				String key = it.next();
//				System.setProperty(key, properties.getProperty(key));
//				String value = properties.getProperty(key).toString();
//				if (key.equals("bucket")) {
//					GameUtils.bucket=value;
//					System.out.println(
//							"当前properties的key为:" + key + "——————/当前properties的value为：" + properties.getProperty(key));
//					continue;
//				}
//				if (key.equals("region")) {
//					GameUtils.region = value;
//					System.out.println(
//							"当前properties的key为:" + key + "——————/当前properties的value为：" + properties.getProperty(key));
//					continue;
//				}
//				if (key.equals("appId")) {
//					GameUtils.appId = value;
//					System.out.println(
//							"当前properties的key为:" + key + "——————/当前properties的value为：" + properties.getProperty(key));
//					continue;
//				}
//				if (key.equals("SecretId")) {
//					GameUtils.SecretId = value;
//					System.out.println(
//							"当前properties的key为:" + key + "——————/当前properties的value为：" + properties.getProperty(key));
//					continue;
//				}
//				if (key.equals("StrSecKey")) {
//					GameUtils.StrSecKey = value;
//					System.out.println(
//							"当前properties的key为:" + key + "——————/当前properties的value为：" + properties.getProperty(key));
//					continue;
//				}
//			}
//		}
//	}

	/**
	 * 加载properties文件
	 *
	 * @param resources
	 * @return
	 */
//	private static Properties loadProperties(String resources) {
//		System.out.println("loadProperties:" + GameSignUtils.class.toString());
//		// 使用InputStream得到一个资源文件
//		InputStream inputstream = PropertiesUtils.class.getClassLoader().getResourceAsStream(resources);
//		// new 一个Properties
//		Properties properties = new Properties();
//		try {
//			// 加载配置文件
//			properties.load(inputstream);
//			return properties;
//		} catch (IOException e) {
//			throw new RuntimeException(e);
//		} finally {
//			try {
//				inputstream.close();
//			} catch (IOException e) {
//				throw new RuntimeException(e);
//			}
//		}
//	}

	/**
	 * 生成channelId
	 *
	 * @param
	 * @return
	 *//*
	public static String getChanelId() {
		// 新的channelId后台自动装配 由频道ID + 当前系统毫秒后八位生成
		String time = System.currentTimeMillis() + "";
		String result = QCloudUtils.bizid +"_"+ time.substring(time.length() - 8, time.length());
		return result;
	}

	*//**
	 * 生成推流地址
	 *
	 * @return
	 *//*
	public static String getRtmpAdress(String channelId) {
		String basic = "rtmp://" + QCloudUtils.bizid + ".livepush.myqcloud.com/live/" + channelId + "?bizid="+QCloudUtils.bizid+"&";
		String txSecret = getSafeUrl(QCloudUtils.lvbKey, channelId,
				DateUtils.getEndTimeOfDate(DateUtils.addDays(new Date(), 1)).getTime() / 1000);
		String rtmpAdress = basic + txSecret;
		return rtmpAdress;
	}

	*//**
	 * 生成rtmp拉流地址
	 *
	 * @return
	 *//*
	public static String getPullRtmp(String channelId) {
		String pullRtmp = "rtmp://"+ QCloudUtils.bizid + ".liveplay.myqcloud.com/live/" + channelId;
		return pullRtmp;
	}

	*//**
	 * 生成FLV拉流地址
	 *
	 * @return
	 *//*
	public static String getPullFlv(String channelId) {
		String pullFlv = "http://"+ QCloudUtils.bizid + ".liveplay.myqcloud.com/live/" + channelId + ".flv";
		return pullFlv;
	}

	*//**
	 * 生成HLS拉流地址
	 *
	 * @return
	 *//*
	public static String getPullHls(String channelId) {
		String pullHls = "http://"+ QCloudUtils.bizid + ".liveplay.myqcloud.com/live/" + channelId + ".m3u8";
		return pullHls;
	}*/

	/*
	 * KEY+ stream_id + txTime
	 */
	private static String getSafeUrl(String key, String streamId, long txTime) {
		String input = new StringBuilder().append(key).append(streamId).append(Long.toHexString(txTime).toUpperCase())
				.toString();

		String txSecret = null;
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			txSecret = byteArrayToHexString(messageDigest.digest(input.getBytes("UTF-8")));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return txSecret == null ? ""
				: new StringBuilder().append("txSecret=").append(txSecret).append("&").append("txTime=")
						.append(Long.toHexString(txTime).toUpperCase()).toString();
	}

	private static String byteArrayToHexString(byte[] data) {
		char[] out = new char[data.length << 1];

		for (int i = 0, j = 0; i < data.length; i++) {
			out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
			out[j++] = DIGITS_LOWER[0x0F & data[i]];
		}
		return new String(out);
	}
	public static Integer[] sameObject(Integer[] a,Integer[]b){
		List<Integer> sameInt = new ArrayList<>();
		for(int i=0;i<b.length;i++)//要将数组短的放在外面，这样能减少循环次数
		{
		  Integer str3 = b[i];
		  for(int j=0;j<a.length;j++)
		  {
		    Integer str4 = a[j];
		    if(str4.equals(str3)) {
				sameInt.add(str4);
			}
		  }
		}
		int size=sameInt.size();
		 Integer[] sameInts = sameInt.toArray(new Integer[size]);
		return sameInts;
	}
	/**
	 * 将字符串转化为int数组
	*
	 * @param str 带解析的字符串
	* @return 转化而成的int数组
	*/
	public static Integer[] parse(String str) {
		Integer length = str.length();
		Integer[] result = new Integer[length];
	 // 依次取得字符串中的每一个字符，并将其转化为数字，放进int数组中
	for (Integer i = 0; i < length; i++) {
	 char c = str.charAt(i);
	 result[i] = Character.getNumericValue(c);
	 }
	 return result;
	}
}
